<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.userName" placeholder="姓名"  style="width:180px;" clearable ></el-input>
				</el-form-item>
				<el-form-item>
					<el-input v-model="filters.account" placeholder="账号"   style="width:180px;" clearable ></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getTeachers">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleImport">导入</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="outSchool" :disabled="this.sels.length===0">移出</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="tableData" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="30">
			</el-table-column>
			<el-table-column type="index" label="序号" width="50" align='center'>
				<template slot-scope="scope">   
                    {{pageSize*(nowPage-1)+scope.$index+1}}
                </template>
			</el-table-column>
			<el-table-column prop="userName" label="姓名" min-width="120" align='center'>
			</el-table-column>
			<el-table-column prop="gender" label="性别" width="50">
				<template slot-scope="scope">
					{{scope.row.gender=="0"?"男":"女"}}
				</template>
			</el-table-column>
			<el-table-column prop="account" label="用户账号" min-width="140" align='center'>
			</el-table-column>
			<el-table-column prop="phaseName" label="学段" min-width="120" align='center'>
			</el-table-column>
			<el-table-column prop="roleName" label="角色" min-width="150" align='center'>
			</el-table-column>
			<el-table-column prop="useType" label="状态" width="50">
				<template slot-scope="scope">
					{{scope.row.useType=="0"?"正常":"停用"}}
				</template>
			</el-table-column>
			<el-table-column label="操作" width="220" align='center' fixed='right'>
				<template slot-scope="scope">
					<el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
					<el-button type="warning" size="small" @click="resetpassword(scope.row)">重置</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-pagination background layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="text-align: center; ">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="editType" :visible.sync="editFormVisible" :close-on-click-modal="false" :before-close="closeDialog" :append-to-body="true" v-loading="editLoading">
			<el-form :model="teacherForm" label-width="120px" :rules="teacherRules" ref="teacherForm">
				<el-form-item label="教师姓名：" prop="userName">
					<el-input v-model="teacherForm.userName" placeholder="请输入教师姓名，最长20个汉字" style="float:left;width:77%;" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="性别：" prop="gender">
					<el-select v-model="teacherForm.gender" placeholder="请选择教师性别" :style="{width: '77%'}">
						<el-option v-for="(item, index) in genderOptions" :key="index" :label="item.label"
							:value="item.value+''" ></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="手机号：" prop="phone">
					<el-input v-model="teacherForm.phone" @keyup.native="validatePhone('teacherForm')" placeholder="请输入手机号" style="float:left;width:77%;"></el-input>
				</el-form-item>
				<el-form-item label="角色：" prop="roleId">
					<el-select v-model="teacherForm.roleId" placeholder="请选择角色" style="float:left;width:77%;">
						<el-option v-for="(item,i) in roleList" :key="i" :label="item.schoolRoleName" :value="item.schoolRoleId"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="教师编号：" prop="teacherNo">
					<el-input v-model="teacherForm.teacherNo" placeholder="请输入教师编号" style="float:left;width:77%;"></el-input>
				</el-form-item>
				<el-form-item label="学段" prop="phaseId">
					<el-radio-group v-model="teacherForm.phaseId" @change="getSubjectList(teacherForm.phaseId)">
						<el-radio v-for="item in phaseList" :key="item.phaseId" :label="item.phaseId">{{item.phaseName}}</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="学科" prop="subjects">
					<el-checkbox-group v-model="teacherForm.subjects">
						<el-checkbox  v-for="(item,index) in subjectList" :label="item.subjectId" :key="index" name="type">{{item.subjectName}}</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="closeDialog">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
		<!-- 教师导入 -->
        <el-dialog title="教师批量导入" width="50%" v-if="importFormVisible" :visible.sync="importFormVisible" @close="closeImport">
            <div v-if="importError == 0">
                <el-upload
                    class="upload-demo"
                    action="#"
                    ref="upload"
                    :limit="1"
                    :on-exceed="beforeUpload"
                    :file-list="uploadFileList"
                    :auto-upload="false">
                    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                    <el-button style="margin-left: 10px;" size="small" type="success" @click="importTeacher">上传导入</el-button>
                </el-upload>
            </div>
            <el-form ref="upLoadTeacherForm" :model="upLoadTeacherForm" label-width="100px" v-if="importError == 1">
                <el-form-item label="错误信息：" style="color:red" prop="name">
                    <el-table :data="errorTable.slice((errorNowPage-1)*errorPageSize,errorNowPage*errorPageSize)" border style="width: 95%">
                        <el-table-column prop="orderNum" label="序号" width="50" align='center'></el-table-column>
                        <el-table-column prop="info" label="错误信息" align='center'></el-table-column>
                    </el-table>
                    <div style="float:left;margin-top:10px;">共&nbsp;{{errorTable.length}}&nbsp;条错误</div>
                    <el-pagination style="float:left;margin-top:5px;"
                            layout="prev, pager, next"
                            @current-change="error_current_change"
                            :total="errorTable.length"
                            :page-size="errorPageSize"
                            :current-page="errorNowPage"
                            background>
                    </el-pagination>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" >
                <el-button v-if="importError == 1" @click="closeImport()" type="primary">确  认</el-button>
                <el-button v-else @click="closeImport()" >取  消</el-button>
            </div>
        </el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	//import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';
	import { SysApi } from '@/api/index'

	export default {
		data() {
			var checkPhone = (rule, value, callback) => {
				if (!value) {
					callback();
				} else {
					const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
				
					if (reg.test(value)) {
						callback();
					} else {
						return callback(new Error('请输入正确的手机号'));
					}
				}
			};
			return {
				filters: {
					schoolId: JSON.parse(sessionStorage.getItem("schoolId")),
					userName:'',
					account:''
				},
				sels: [],//列表选中列
				tableData: [],
				total: 0,
				listLoading: true,
				phaseList: [],
				subjectList: [],
				subjects: [],
				phaseId: '',
				schoolName: '',
				schoolId:  JSON.parse(sessionStorage.getItem("schoolId")),
				provinceCode: JSON.parse(sessionStorage.getItem("provinceCode")),
				cityCode: JSON.parse(sessionStorage.getItem("cityCode")),
				districtCode: JSON.parse(sessionStorage.getItem("districtCode")),

				//教师信息表单
				teacherForm: {
					schoolId: JSON.parse(sessionStorage.getItem("schoolId")),
					schoolName: JSON.parse(sessionStorage.getItem("schoolName")),
					provinceCode: JSON.parse(sessionStorage.getItem("provinceCode")),
					cityCode: JSON.parse(sessionStorage.getItem("cityCode")),
					districtCode: JSON.parse(sessionStorage.getItem("districtCode")),
					userId: '',
					userName: '',
					phone: '',
					gender: '',
					teacherNo: '',
					phaseId: '',
					roleId: '',
					type: '',
					useType: '',
					subjects: [],
				},

				genderOptions: [{
					"label": "男",
					"value": 0
				}, {
					"label": "女",
					"value": 1
				}],

				editType: '',

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,

				importFormVisible : false, // 导入界面是否显示

				uploadFileList: [],
				importError: 0,
				upLoadTeacherForm:{}, 
				errorTable:[],
				errorPageSize:10,
				errorNowPage:1,

				teacherRules: { //教师信息表单验证
					userName:[
						{ required: true, message: '请输入教师姓名', trigger: 'blur' },
						{ min: 1, max: 20, message: '姓名长度为 1 到 20 个字符', trigger: ['blur','change'] }
					],
					phone:[
						{ required: true, message: '请输入教师手机号', trigger:'blur' },
						{ validator: checkPhone, trigger: ['blur','change'] }
					],
					gender:[
						{ required: true, message: '请选择性别', trigger: 'blur' },
					],
					roleId:[
						{ required: true, type: 'number', message: '请选择角色', trigger: 'blur' },
					],
					provinceCode:[
						{ required: true, message: '请选择省', trigger: 'blur' },
					],
					cityCode:[
						{ required: true, message: '请选择市', trigger: 'blur' },
					],
					districtCode:[
						{ required: true, message: '请选择区/县', trigger: 'blur' },
					],
					schoolId:[
						{ required: true, type: 'number',message: '请选择所属学校', trigger: 'blur' }
					],
					phaseId:[
						{ required: true, type: 'number',message: '请选择学段', trigger: 'blur' }
					]
            },
            roleList: [],
            pageSize: 10,
            nowPage: 1,
            schoolList: [],
            roleLevel: 0,

			}
		},
		created(){
			if(this.$route.params.schoolId != undefined){
				sessionStorage.setItem("schoolId", JSON.stringify(this.$route.params));
				this.schoolId = this.$route.params.schoolId;
			}else{
				this.schoolId = JSON.parse(sessionStorage.getItem("schoolId"));
			}  
			//获取教师列表
			this.getTeachers();
			//获取角色列表
			this.getRoleList();
			//获取学段列表
			this.getPhaseList();
		},
		mounted() {
			 //获取教师列表
			this.getTeachers();
		},
		methods: {
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
				this.nowPage = val;
				this.getTeachers();
			},
			//获取角色列表
			getRoleList(){
				let params = {
					schoolId: this.schoolId
				};
			SysApi.getSchoolRoleList(params, res => {
					this.roleList = res;
				}, (errorType, error) => {
				})
			},
			//获取学段列表
			getPhaseList(){
				let params = {
					schoolId: this.schoolId
				};
				SysApi.getSchoolPhaseList(params, res => {
					if (res!=null)
					{
						this.phaseList = res;
					}
				}, (errorType, error) => {
				})
			},
			// 获得学科列表
			getSubjectList(phaseId){
				
				let params = {
						phaseId: phaseId
					};
	
					SysApi.getSubjectList(params, res => {
						if (res!=null)
						{
							this.subjectList = res;

							if (this.phaseId != phaseId)
							{
								this.teacherForm.subjects = [];
							}
							else
							{
								this.teacherForm.subjects = this.subjects;
							}
						}
					}, (errorType, error) => {

					})
			},
			//获取用户列表
			getTeachers() {
				let params = {
					pageNum: this.nowPage,
					pageSize: this.pageSize,
					schoolId: this.schoolId,
					userName: this.filters.userName,
					account: this.filters.account,
					// roleId: this.filters.roleId,
				};
				this.listLoading = true;

				SysApi.getSchoolTeacherListPage(params,res =>{
					this.total = res.total;
					this.tableData = res.list;
					this.listLoading = false;
				}, (errorType, error) => {
					this.listLoading = false;
				})


			},
			//教师手机号，只能输入正整数限制
			validatePhone(str){
				if(str== "teacherForm"){
					this.teacherForm.phone = this.teacherForm.phone.replace(/[^\.\d]/g,'');
					this.teacherForm.phone = this.teacherForm.phone.replace('.','');
				}else{
					this.filters.phone = this.filters.phone.replace(/[^\.\d]/g,'');
					this.filters.phone = this.filters.phone.replace('.','');
				}
			},
			//改变角色
			// changeRole(roleId){
			// 	for(let i = 0; i < this.roleList.length; i++){
			// 		if(this.roleList[i].roleId == roleId){
			// 			this.roleLevel = this.roleList[i].roleLevel
			// 		}
			// 	}
			// },
			//删除
			handleDel: function (row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					
					this.listLoading = true;
		
					let params = {
						 userId: row.userId,
						 schoolId: row.schoolId
						 };

					SysApi.deleteTeacher(params,res =>{
						this.listLoading = false;
						{
							this.$message({
								message: '删除成功',
								type: 'success'
							});
						}
						this.getTeachers();
					}, (errorType, error) => {
						this.listLoading = false;
					}).catch((error) => {
						this.listLoading = false;
					})
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (row) {
				this.editType = "编辑";
				this.editLoading = true;

				this.userId = row.userId;

				this.teacherForm = {
					userId: row.userId,
					userName: row.userName,
					phone: row.phone,
					roleId: row.roleId,
					gender: row.gender,
					teacherNo: row.teacherNo,
					provinceCode: row.provinceCode,
					cityCode: row.cityCode,
					districtCode: row.districtCode,
					schoolId: row.schoolId,
					phaseId: row.phaseId,
					subjects: row.subjects
				},

				this.phaseId = row.phaseId;
				this.subjects = this.teacherForm.subjects;
				this.getSubjectList(row.phaseId);

				var roleIndex = 0; 
				for(let role in this.roleList){
					
					if (this.roleList[role].schoolRoleId == row.roleId)
					{
						roleIndex = this.roleList[role].schoolRoleId;
						break;
					}
				}

				if (roleIndex==0)
				{
					this.teacherForm.roleId = '';
				}

				this.editFormVisible = true;
				this.editLoading = false;
				//this.this.editLoading = false;teacherForm = Object.assign({}, row);
				
			},
			//显示新增界面
			handleAdd: function () {

				this.editType = "新增";
				this.editLoading = true;

				this.teacherForm.userId =  '';
				this.teacherForm.userName =  '';
				this.teacherForm.gender =  '';
				this.teacherForm.phone =  '';
				this.teacherForm.roleId = '';
				this.teacherForm.provinceCode = this.provinceCode;
				this.teacherForm.cityCode =  this.cityCode;
				this.teacherForm.districtCode =  this.districtCode;
				this.teacherForm.schoolId =  this.schoolId;
				this.teacherForm.phaseId = '';
				this.teacherForm.teacherNo = '';
				this.teacherForm.subjects = [];
				this.phaseId = '';
				this.subjects = [];
				this.subjectList = [];
				
				this.editFormVisible = true;
				this.editLoading = false;
		
			},
			//编辑
			editSubmit: function () {
				this.$refs.teacherForm.validate((valid) => {
					if (valid) {
							//NProgress.start();
							let params = Object.assign({}, this.teacherForm);

							SysApi.saveTeacher(params,res =>{
								this.listLoading = false;
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['teacherForm'].resetFields();
								this.editFormVisible = false;
								this.getTeachers();
							}, (errorType, error) => {
	
							})
							
					}
				});
			},
			resetpassword(row){
				this.$confirm('是否重置密码', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					SysApi.resetTeacher({
						userId: row.userId
					}, res => {
						this.$message({type: 'success', message: '重置密码成功!'})
						this.getTeachers();
					}, (errorType, error) => {
						this.$message({type: 'error', message: '重置密码失败!'})
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量移出
			outSchool: function () {
				var ids = this.sels.map(item => item.userId).toString();
				this.$confirm('确认将选中教师移出学校吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;

					let params = {
						 teacherIds: ids,
						 schoolId: this.schoolId
						 };
					SysApi.outSchoolTeacher(params).then((res) => {
						this.listLoading = false;
						
						this.$message({
							message: '移出成功',
							type: 'success'
						});
						this.getTeachers();
					});
				}).catch(() => {

				});
			},
			closeDialog: function () {
				this.$refs['teacherForm'].resetFields();
				this.editFormVisible = false;
			},
			//显示导入界面
			handleImport() {
				this.importFormVisible = true;
				
			},
			//导入教师
			importTeacher(){
				if(this.$refs['upload'].uploadFiles.length > 0){
					const formData = new FormData();
					const file = this.$refs.upload.uploadFiles[0];
				// const headerConfig = { headers: { 'Content-Type': 'multipart/form-data' } };
					formData.append('file', file.raw);
					formData.append("schoolId", this.schoolId);

					SysApi.importTeacher(formData, res => {
						if (res.statusinfo === 'error') {
							
							this.errorTable = res.errordata || [];
							this.errorNowPage = 1;
							this.nowPage = 1;
							this.importError = 1;
							this.getTeachers();
						}else{
							this.getTeachers();
							this.closeImport();
							this.importError = 0;
							this.nowPage = 1;
							this.$message({type: 'success', message: '导入成功!'})
						}
					});
						
				}else{
					this.$message({
						message: '请选择要上传的文件',
						type: 'warning'
					});
				}
			},
			//导入教师窗口关闭
			closeImport(){
				this.importFormVisible = false;
				this.uploadFileList = [];
				this.importError = 0;
			},
			beforeUpload(files, uploadFileList) {
				this.$message.warning(`只能选择 1 个文件，目前共选择了 ${files.length + uploadFileList.length} 个文件`);
			},
			error_current_change(errorNowPage){
				this.errorNowPage = errorNowPage;
			},
			
		},
		
	}

</script>

<style>
.el-table >.el-table__fixed {
    height: 100% !important; 
  }
.el-table >.el-table__fixed-right {
    height: 100% !important; 
  }
.el-table--scrollable-x .el-table__body-wrapper {
    z-index: 1;
  }
</style>